import saleOrdersAPI from '../../../common/api/breedsales/orderbills.api.js';
import doT from '../../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from '../../../common/dictionary/dictionary-type.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from '../../../common/api/file-request.js';
import { Select2Page } from '../../../common/serve-request.js';

(function (window, document, $) {
    const toolbarTemplate = `<div class="toolbar" id="me-date-screening">
<div class="toolbar-inner">
<span style='margin:0 auto;margin-top:10px'>请选择业务日期</span>
<a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a>
</div>
</div>`;

    const _json = Utils.ParsingUrl(window.location);
    const addsaleTemplate = doT.template($('#addsaleorders-template').text());
    const _page = {
        searchInfo: '',
        startDate: '',
        endDate: '',
        billStatus: 3,
        orgId: '',
        fitlerOrgs: [],
        pageSize: 10,
        pageIndex: 0,
        totalPages: -1,
    };

    let _vm,
        _ownOrgs = [],
        _stuffInfo = [],
        _pickerTime,
        _deliveryTime,
        savetype,
        uersInfo,
        getMainMessage = [],
        custom,
        saleOrgsinfo,
        getEntryInfo = [],
        operaEntry,
        operaEntryId,
        nextEntryId = 0,
        timer = null,
        addstyleEntry,
        edistyleEntry,
        renderEntryInfo = [],
        getMainInfo = [],
        transTypeList,
        entriesmater = {};
    let _levelType = [],
        _personOrg = [],
        _pigTypeList = [];

    $(function () {
        _vm = new Vue({
            el: '#addsaleorders-form',
            data() {
                return {
                    bizDate: '',
                    saleOrgId: '',
                    saleOrgName: '',
                    salePerId: '',
                    salePerName: '',
                    salePerNumCode: '',
                    salePerPhone: '',
                    cstmId: '',
                    cstmName: '',
                    cstmNumCode: '',
                    cstmPhone: '',
                    pigType: '',
                    tranType: '',
                    totalCount: 0,
                    remark: '',
                    attaches: '',
                    entries: [
                        {
                            seq: 0,
                            farmOrgId: '',
                            farmOrgName: '',
                            deiverId: '',
                            deiverName: '',
                            deiverNumCode: '',
                            deiverPhone: '',
                            shipRegion: '',
                            shipAddress: '',
                            deliveryRegion: '',
                            deliveryAddress: '',
                            specLevel: '',
                            carNo: '',
                            transferCarNo: '',
                            planQty: 0,
                            unitPrice: 0,
                            weight: 0,
                            estimatedAvgWeight: 0,
                            materialId: '',
                            materialName: '',
                            materialNumCode: '',
                            baseMeasureUnit: '',
                            subMeasureUnit: '',
                            breedBatchId: '',
                            breedBatchName: '',
                        },
                    ],
                    uploadCount: 0,
                    images: [], ///处理weui自带上传插件回显重新上传时的问题
                    attaches: [],
                    page: { ..._page },
                };
            },
            methods: {
                submit() {
                    savedata();
                },
            },
        });
        //_ediCommand()
        ctlReturn();
        selfAdaption();
        _initCommand();
        _datetimePickerInit();
        _deliveryPickerInit();
        custominfo();
        _delSalesEntry();
        _ediSalesEntry();
        uploadInit();
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    // 初始化数据
    const _initCommand = async () => {
        //猪只类型
        await requestDict(DictionaryType.PIG_FIXEDPRICE_TYPE).then((res) => {
            _pigTypeList = res.data;
            $('#pigType')
                .empty()
                .select2({
                    placeholder: '请选择猪只类型...', //默认文字提示
                    language: 'zh-CN', //汉化
                    data: res.data.map((item) => {
                        return {
                            id: item.value,
                            text: item.displayName,
                        };
                    }),
                });
            $('#pigType').setSelectValue();
        });
        // 选择猪只类型 清除校验
        $('#pigType').on('select2:select', function () {
            _vm.pigType = $(this).select2('data')[0]?.id;
        });

        //运输类型
        await requestDict(DictionaryType.CARGO_TYPE).then((res) => {
            transTypeList = res.data.filter((item) => item.value != '2');
            $(`#tranType`)
                .empty()
                .select2({
                    placeholder: '请选择运输类型...', //默认文字提示
                    language: 'zh-CN', //汉化
                    allowClear: true, //允许清空
                    data: transTypeList.map((item) => {
                        return {
                            id: item.value,
                            text: item.displayName,
                        };
                    }),
                });
            $(`#tranType`).setSelectValue();
        });

        // 选择猪只类型 清除校验
        $('#tranType').on('select2:select', function () {
            _vm.tranType = $(this).select2('data')[0]?.id;
        });

        //销售品类
        let type = await requestDict(DictionaryType.LEVEL_TYPE);
        _levelType = type.data;

        getMainMessage = JSON.parse(Utils.GetSessionStorage('getMainMessage'));
        $('#selCustomerInfos').prop('disabled', false);

        $('#tranTypeDiv').css('display', 'none');
        if (Utils.IsNotNull(getUrlKey('id'))) {
            $('#informationSubmit').text('保存');
            $('title').text('销售订单-编辑');
            $('#tranTypeDiv').css('display', 'block');
            $('#selCustomerInfos').prop('disabled', true);
            $('#saleOrgId').prop('disabled', true);

            if (!Utils.IsNotNull(getUrlKey('nextEntryId'))) {
                await saleOrdersAPI.querySalesInfo(getUrlKey('id')).then((res) => {
                    _vm.bizDate = res.bizDate.split(' ')[0].replace(/\//g, '-');
                    _vm.saleOrgId = res.saleOrgId;
                    _vm.saleOrgName = res.saleOrgName;
                    _vm.salePerId = res.salePerId;
                    _vm.salePerName = res.salePerName;
                    _vm.salePerNumCode = res.salePerNumCode;
                    _vm.cstmId = res.cstmId;
                    _vm.cstmName = res.cstmName;
                    _vm.cstmNumCode = res.cstmNumCode;
                    _vm.pigType = res.pigType;
                    _vm.tranType = res.tranType;
                    $('#remark').val(res.remark);
                    $('#selCustomerInfos').setSelectValue(res.cstmId, res.cstmName);
                    $('#salePerId').setSelectValue(res.salePerId, res.salePerName);
                    $('#pigType').val(_vm.pigType).trigger('change');
                    $('#tranType').val(_vm.tranType).trigger('change');

                    if (Utils.IsNotNull(res.attaches)) {
                        $('#uploaderFiles').empty();
                        _images(res.attaches);
                    }
                    getEntryInfo = res.entreis;
                    _initEntry();
                });
            }
        }
        _initseller();
        saleOrgs();

        //查询登录用户拥有的组织信息
        let personOrgs = await saleOrdersAPI.postUserOrgsList();
        _personOrg = [];
        personOrgs.forEach((item) => {
            if (item.optTag == 1 && item.tags.indexOf('210') !== -1) {
                _personOrg.push(item.oId);
            }
        });

        // 获取分录信息
        getEntryInfo = JSON.parse(Utils.GetSessionStorage('getEntryInfo'));

        if (Utils.IsNotNull(getEntryInfo)) {
            renderEntryInfo = JSON.parse(JSON.stringify(getEntryInfo));
            let _cost = [];
            let _num = [];
            let _weight = [];
            $.each(renderEntryInfo, function (i, v) {
                _cost.push(v.unitPrice == '' ? 0 : v.unitPrice);
                _num.push(v.planQty || v.orderCount);
                _weight.push(v.estimatedAvgWeight == '' ? 0 : v.estimatedAvgWeight);
            });

            $('#totalCost').text(eval(_cost.join('+')));
            $('#totalNum').text(eval(_num.join('+')));
            $('#totalWeight').text(Utils.toThousands(eval(_weight.join('+'))));

            renderEntryInfo = renderEntryInfo.map((item) => {
                let specLevelType = '';
                let detailDeliveryAddress = '';
                if (Utils.IsNotNull(_levelType.find((s) => s.value == item.specLevel))) {
                    specLevelType = _levelType.find((s) => s.value == item.specLevel).displayName;
                } else {
                    specLevelType = item.specLevel;
                }
                //收货地址
                if (Utils.IsNotNull(item.deliveryRegion)) {
                    let areaId = item.deliveryRegion.split('|');
                    let split = areaId[1].split(';');
                    detailDeliveryAddress = split[0] + split[1] + split[2] + split[3] + item.deliveryAddress;
                } else {
                    detailDeliveryAddress = item.deliveryAddress;
                }
                return { ...item, specLevelType, detailDeliveryAddress };
            });
            $('#salesEntry').empty().append(addsaleTemplate(renderEntryInfo));
        }
        // 获取下一个分录的序号
        if (Utils.IsNotNull(getUrlKey('nextEntryId'))) {
            nextEntryId = getUrlKey('nextEntryId');
        }
        // 点击添加销售列表
        $('#add-saleEntry').on('click', function () {
            let cstmId = '';
            if (!Utils.IsNotNull($('#selCustomerInfos').val()) && !Utils.IsNotNull(_json.cstmId)) {
                return $.toptip(`请先选择客户!`, 'warning');
            } else {
                cstmId = $('#selCustomerInfos').val() == null ? _json.cstmId : $('#selCustomerInfos').val();
            }
            //存储数据
            let _attaches = [];
            if (Utils.IsNotNull(_vm.images)) {
                $.each(_vm.images, function (i, v) {
                    _attaches.push(v.imageId);
                });
            } else {
                $.each(_vm._attaches, function (i, v) {
                    _attaches.push(v);
                });
            }

            getMainMessage = [];
            entriesmater = {
                bizDate: _vm.bizDate,
                saleOrgId: _vm.saleOrgId,
                saleOrgName: _vm.saleOrgName,
                salePerId: _vm.salePerId,
                salePerName: _vm.salePerName,
                salePerNumCode: _vm.salePerNumCode,
                salePerPhone: _vm.salePerPhone,
                cstmId: cstmId,
                cstmName: _vm.cstmName,
                cstmNumCode: _vm.cstmNumCode,
                cstmPhone: _vm.cstmPhone,
                pigType: _vm.pigType,
                tranType: _vm.tranType,
                totalCount: $('#totalCost').text(),
                remark: $('#remark').val(),
                attaches: _attaches.join(','),
            };
            getMainMessage.push(entriesmater);
            JSON.stringify(Utils.SetSessionStorage('getMainMessage', getMainMessage));

            if (Utils.IsNotNull(getUrlKey('id'))) {
                location.href = `../saleorders/saleordersentry.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}&id=${getUrlKey('id')}&orgId=${$('#saleOrgId').val()}&cstmId=${cstmId}`;
            } else {
                location.href = `../saleorders/saleordersentry.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}&orgId=${$('#saleOrgId').val()}&cstmId=${cstmId}`;
            }
            _mainInfo();
        });
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../saleorders/saleorders.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                bottom: '-6rem',
                transition: 'all .ls ease-in',
            });
        });

        //新增销售计划选择
        $(document).on('click', '#add-salePlan', function () {
            let cstmId = '';
            if (!Utils.IsNotNull($('#saleOrgId').val())) {
                return $.toptip(`请先选择销售组织!`, 'warning');
            }
            if (!Utils.IsNotNull($('#selCustomerInfos').val()) && !Utils.IsNotNull(_json.cstmId)) {
                return $.toptip(`请先选择客户!`, 'warning');
            } else {
                cstmId = $('#selCustomerInfos').val() == null ? _json.cstmId : $('#selCustomerInfos').val();
            }

            $('#pop').css('display', 'block');
            $('.show-box').css('display', 'block');
            $('.show-box').css({
                bottom: '0',
                transition: 'all .ls ease-in',
            });
            $('#saleplans-list').empty();
            _vm._data.page = {
                searchInfo: '',
                startDate: '',
                endDate: '',
                billStatus: 3,
                orgId: '',
                fitlerOrgs: _personOrg,
                pageSize: 10,
                pageIndex: 0,
                totalPages: -1,
            };
            _querySalePlansList(); //查询销售计划列表
        });
        //TODO : 销售计划上拉加载
        $('#saleplans-list')
            .infinite()
            .on('infinite', function () {
                let _data = _vm._data.page;
                if (_data.pageIndex == _data.totalPages) return;
                let self = this;
                if (self.loading) return;
                self.loading = true;
                setTimeout(function () {
                    _querySalePlansList();
                    self.loading = false;
                }, 500); //模拟延迟
            });
        //销售计划选中确认
        $('#saleplansSubmit').on('click', function () {
            let salePlans = [];
            let checkSale = $('#saleplans-list').find($('input[type=checkbox]:checked'));
            let saleList = $('#salesEntry').find('.report-contents-item-box');
            for (var i = 0; i < checkSale.length; i++) {
                let res = checkSale[i].parentNode.dataset;
                if (nextEntryId == 0) {
                    nextEntryId = saleList.length + 1;
                } else {
                    nextEntryId = _json.nextEntryId == undefined ? nextEntryId : Number(_json.nextEntryId);
                }
                let item = {
                    seq: nextEntryId,
                    farmOrgId: res.farmorgid,
                    farmOrgName: res.farmorgname,
                    deiverId: '',
                    deiverName: '',
                    deiverNumCode: '',
                    deiverPhone: '',
                    shipRegion: '',
                    shipAddress: res.farmorgname,
                    deliveryRegion: '',
                    deliveryAddress: '',
                    specLevel: res.speclevel,
                    specLevelType: _levelType.find((s) => s.value == res.speclevel).displayName,
                    carNo: '',
                    transferCarNo: '',
                    planQty: res.count,
                    unitPrice: '',
                    weight: '',
                    estimatedAvgWeight: res.avgweight,
                    materialId: '',
                    materialName: '',
                    materialNumCode: '',
                    baseMeasureUnit: '',
                    subMeasureUnit: '',
                    breedBatchId: res.breedbatchid,
                    breedBatchName: res.breedbatchname,
                };
                salePlans.push(item);
                getEntryInfo.push(item);
                nextEntryId++;
            }
            $('#salesEntry').append(addsaleTemplate(salePlans));
            JSON.stringify(Utils.SetSessionStorage('getEntryInfo', getEntryInfo));

            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                bottom: '-6rem',
                transition: 'all .ls ease-in',
            });
            _initEntry();
        });
    };
    // 保存分录以上的信息
    const _mainInfo = () => {
        let _mainInfo = { saleOrgId: _vm.saleOrgId, cstmId: _vm.cstmId, salePerId: _vm.salePerId, bizDate: _vm.bizDate, deliveryDate: _vm.deliveryDate, shippingType: _vm.shippingType, pigType: _vm.pigType, tranType: _vm.tranType };
        JSON.stringify(Utils.SetSessionStorage('mainInfo', _mainInfo));
    };
    // 初始化销售组织
    const saleOrgs = async () => {
        _stuffInfo = await saleOrdersAPI.getUserInfo();
        _ownOrgs = await saleOrdersAPI.postUserOrgsList();
        saleOrdersAPI.getOrgsListType().then((res) => {
            let sale = res.filter((s) => s.typeValue == true);
            let obj = _ownOrgs.filter((item) => sale.some((item2) => item2.id == item.oId));
            let ownAccount = obj.find((s) => s.oId == _stuffInfo.curOrgId);
            $('#saleOrgId').select2({
                placeholder: '请选择销售组织...', //默认文字提示
                language: 'zh-CN', //汉化
                data: obj.map((item) => {
                    return {
                        id: item.oId,
                        name: item.oName,
                        text: `${item.oName}(${item.oNumCode})`,
                    };
                }),
            });
            $('#saleOrgId').setSelectValue();

            //解决字段过长
            $('#saleOrgId').on('change', function () {
                saleOrgsinfo = cutstr($('#select2-saleOrgId-container').text(), 22);
                $('#select2-saleOrgId-container').text(`${saleOrgsinfo}`);
                if (Utils.IsNotNull($('#saleOrgId').select2('data')[0])) {
                    _vm.saleOrgId = $('#saleOrgId').select2('data')[0].id;
                    _vm.saleOrgName = $('#saleOrgId').select2('data')[0].name;
                }
            });

            $('#saleOrgId').on('select2:select', function () {
                getEntryInfo = [];
                _initEntry();
                $('#totalNum').text(0);
                $('#totalWeight').text(0);
            });

            if (Utils.IsNotNull(getMainMessage)) {
                $('#businessTime').val(getMainMessage[0].bizDate);
                $('#saleOrgId').val(getMainMessage[0].saleOrgId).trigger('change');
                $('#salePerId').val(getMainMessage[0].salePerId).trigger('change');
                $('#selCustomerInfos').val(getMainMessage[0].cstmId).trigger('change');

                $('#selCustomerInfos').setSelectValue(getMainMessage[0].cstmId, getMainMessage[0].cstmName);
                $('#salePerId').setSelectValue(getMainMessage[0].salePerId, getMainMessage[0].salePerName);
                $('#remark').val(getMainMessage[0].remark);
                if (Utils.IsNotNull(getMainMessage[0].attaches) && !Utils.IsNotNull(getUrlKey('id'))) {
                    $('#uploaderFiles').empty();
                    _images(getMainMessage[0].attaches);
                }

                _vm.cstmId = getMainMessage[0].cstmId;
                _vm.cstmName = getMainMessage[0].cstmName;
                _vm.cstmNumCode = getMainMessage[0].cstmNumCode;
                _vm.pigType = getMainMessage[0].pigType;
                _vm.tranType = getMainMessage[0].tranType;
                _vm.bizDate = getMainMessage[0].bizDate;
                _vm.salePerId = getMainMessage[0].salePerId;
                _vm.salePerName = getMainMessage[0].salePerName;
                _vm.salePerNumCode = getMainMessage[0].salePerNumCode;
                _vm.attaches = getMainMessage[0].attaches.split(',');
                $('#pigType').val(_vm.pigType).trigger('change');
                $('#tranType').val(_vm.tranType).trigger('change');
            }
            if (Utils.IsNotNull(getUrlKey('id'))) {
                $('#saleOrgId').setSelectValue(_vm.saleOrgId, _vm.salePerName);
                $('#saleOrgId').prop('disabled', true);
            } else if (Utils.IsNotNull(ownAccount)) {
                $('#saleOrgId').val(ownAccount.oId).trigger('change');
                $('#saleOrgId').change();
            } else {
                $('#saleOrgId').change();
            }
        });
    };
    // 初始化客户信息
    const custominfo = () => {
        Select2Page(
            $(`#selCustomerInfos`),
            `${Utils.CurDomain.MasterDataUrl}/yycustomers/by/q`,
            (params) => {
                return {
                    SearchInfo: params.term,
                    pageSize: 10,
                    pageIndex: (params.page || 1) - 1,
                };
            },
            'GET',
            {
                placeholder: '请选择客户...', //默认文字提示
                templateResult: function (res) {
                    return `${res.name}(${res.numCode})`;
                },
            },
        );
        $('#selCustomerInfos').setSelectValue();
        //$('#selCustomerInfos').on('change', function () {
        //    custom = cutstr($('#select2-selCustomerInfos-container').text(), 22)
        //    $('#select2-selCustomerInfos-container').text(`${custom}`)
        //    if (Utils.IsNotNull($('#selCustomerInfos').select2('data')[0])) {
        //        _vm.cstmId = $('#selCustomerInfos').select2('data')[0].id
        //        _vm.cstmName = $('#selCustomerInfos').select2('data')[0].name
        //        _vm.cstmNumCode = $('#selCustomerInfos').select2('data')[0].numCode
        //    }
        //});
        if (Utils.IsNotNull(_vm.cstmId)) {
            $('#selCustomerInfos').setSelectValue(_vm.cstmId, _vm.cstmName);
            $('#selCustomerInfos').val(_vm.cstmId);
            $('#selCustomerInfos').prop('disabled', true);
        }
        //选择客户后赋值
        $('#selCustomerInfos').on('select2:select', function () {
            _vm.cstmId = $('#selCustomerInfos').select2('data')[0].id;
            _vm.cstmNumCode = $('#selCustomerInfos').select2('data')[0].numCode;
            _vm.cstmName = $('#selCustomerInfos').select2('data')[0].name;

            getEntryInfo = [];
            _initEntry();
            $('#totalNum').text(0);
            $('#totalWeight').text(0);
        });
        if (Utils.IsNotNull(_json.cstmId)) {
            $('#selCustomerInfos').setSelectValue(_json.cstmId);
            $('#selCustomerInfos').val(_json.cstmId);
        }
    };

    // 初始化员工
    const _initseller = () => {
        Select2Page(
            $(`#salePerId`),
            `${Utils.CurDomain.EmployeeMgtUrl}/emplrecds/by/q`,
            (params) => {
                if (Utils.IsNotNull(params.term)) {
                    return {
                        Status: true,
                        SearchInfo: params.term,
                        pageSize: 10,
                        pageIndex: (params.page || 1) - 1,
                    };
                } else {
                    return {
                        Status: true,
                        pageSize: 10,
                        pageIndex: (params.page || 1) - 1,
                    };
                }
            },
            'GET',
            {
                placeholder: '请选择销售员...', //默认文字提示
                templateResult: function (res) {
                    return `${res.name}(${res.numCode})`;
                },
            },
        );
        $('#salePerId').setSelectValue();
        if (Utils.IsNotNull(_vm.salePerId)) {
            $('#salePerId').setSelectValue(_vm.salePerId, _vm.salePerName);
            $('#salePerId').val(_vm.salePerId);
        }
        $('#salePerId').on('select2:select', function () {
            _vm.salePerId = $('#salePerId').select2('data')[0].id;
            _vm.salePerNumCode = $('#salePerId').select2('data')[0].numCode;
            _vm.salePerName = $('#salePerId').select2('data')[0].name;
        });
    };

    //业务日期控件初始化
    const _datetimePickerInit = () => {
        initCurrentDay();
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        // 开始日期
        $('#search-date').on('click', function (e) {
            e.stopPropagation();
            $('#search-date').picker('open');
            _pickerDate();
        });
        $('#search-date').datetimePicker({
            toolbarTemplate: toolbarTemplate,
            toolbarCloseText: '确定',
            toolbarCancelText: '取消',
            yearSplit: '年',
            monthSplit: '月',
            dateSplit: '日',
            times: function () {
                return [];
            },
            //确定选择时的操作
            onClose: function (picker) {
                let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2];
                _pickerTime = '';
                _pickerTime = value;
            },
        });
    };
    //业务日期确认事件
    const _pickerDate = () => {
        $(document).on('click', '.close-picker', function () {
            $('#businessTime').val(_pickerTime);
            _vm.bizDate = _pickerTime;
        });
    };
    // 业务日期获取当天
    const initCurrentDay = () => {
        let todayDate = moment().format('YYYY-MM-DD');
        $('#businessTime').val(todayDate);
        _vm.bizDate = todayDate;
    };

    //发货日期控件初始化
    const _deliveryPickerInit = () => {
        initCurrentDay();
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        // 开始日期
        $('#delivery-date').on('click', function (e) {
            e.stopPropagation();
            $('#delivery-date').picker('open');
            _deliverypickerDate();
        });
    };
    //发货日期确认事件
    const _deliverypickerDate = () => {
        $(document).on('click', '.close-picker', function () {
            $('#deliveryDate').val(_deliveryTime);
            _vm.deliveryDate = _deliveryTime;
        });
    };
    // 删除分录
    const _delSalesEntry = () => {
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            operaEntry = $(this).parents('.report-contents-item-box').attr('id');
            operaEntryId = operaEntry.substr(operaEntry.length - 1);
            deltips();
        });
    };
    // 删除分录提示
    const deltips = () => {
        $.modal({
            autoClose: false,
            title: '删除提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '确定',
                    onClick: function () {
                        getEntryInfo.splice(operaEntryId - 1, 1);
                        _initEntry();
                        $.closeModal();
                    },
                },
            ],
        });
    };
    // 编辑分录
    const _ediSalesEntry = () => {
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit]', function () {
            let cstId = '';
            operaEntry = $(this).parents('.report-contents-item-box').attr('id');
            cstId = $(this).parents('.report-contents-item-box').attr('data-customer');
            if (!Utils.IsNotNull(cstId)) {
                cstId = $('#selCustomerInfos').val() == null ? _json.cstmId : $('#selCustomerInfos').val();
            }
            //存储数据
            let _attaches = [];
            $.each(_vm.images, function (i, v) {
                _attaches.push(v.imageId);
            });
            getMainMessage = [];
            entriesmater = {
                bizDate: _vm.bizDate,
                saleOrgId: _vm.saleOrgId,
                saleOrgName: _vm.saleOrgName,
                salePerId: _vm.salePerId,
                salePerName: _vm.salePerName,
                salePerNumCode: _vm.salePerNumCode,
                salePerPhone: _vm.salePerPhone,
                cstmId: _vm.cstmId,
                cstmName: _vm.cstmName,
                cstmNumCode: _vm.cstmNumCode,
                cstmPhone: _vm.cstmPhone,
                pigType: _vm.pigType,
                tranType: _vm.tranType,
                totalCount: $('#totalCost').text(),
                remark: $('#remark').val(),
                attaches: _attaches.join(','),
            };
            getMainMessage.push(entriesmater);
            JSON.stringify(Utils.SetSessionStorage('getMainMessage', getMainMessage));

            operaEntryId = operaEntry.substr(operaEntry.length - 1);
            if (Utils.IsNotNull(getUrlKey('id'))) {
                location.href = `../saleorders/saleordersentry.html?v=${Utils.GetTime()}&operaEntryId=${operaEntryId}&nextEntryId=${nextEntryId}&id=${getUrlKey('id')}&orgId=${$('#saleOrgId').val()}&cstmId=${cstId}`;
            } else {
                location.href = `../saleorders/saleordersentry.html?v=${Utils.GetTime()}&operaEntryId=${operaEntryId}&nextEntryId=${nextEntryId}&orgId=${$('#saleOrgId').val()}&cstmId=${cstId}`;
            }
            _mainInfo();
        });
    };

    // 编辑和删除分录后，重新渲染分录
    const _initEntry = () => {
        getEntryInfo.forEach(function (item, index) {
            item.seq = index + 1;
        });
        JSON.stringify(Utils.SetSessionStorage('getEntryInfo', getEntryInfo));
        nextEntryId = Number(getEntryInfo.length) + 1;
        renderEntryInfo = JSON.parse(JSON.stringify(getEntryInfo));
        let _cost = [],
            _num = [],
            _weight = [];
        $.each(renderEntryInfo, function (i, v) {
            _cost.push(v.unitPrice == '' ? 0 : v.unitPrice);
            _num.push(v.planQty || v.orderCount);
            _weight.push(v.estimatedAvgWeight == '' ? 0 : v.estimatedAvgWeight);
        });

        $('#totalCost').text(eval(_cost.join('+')));
        $('#totalNum').text(eval(_num.join('+')));
        $('#totalWeight').text(Utils.toThousands(eval(_weight.join('+'))));
        renderEntryInfo = renderEntryInfo.map((item) => {
            let specLevelType = '',
                detailDeliveryAddress = '';
            if (Utils.IsNotNull(_levelType.find((s) => s.value == item.specLevel))) {
                specLevelType = _levelType.find((s) => s.value == item.specLevel).displayName;
            } else {
                specLevelType = item.specLevel;
            }
            //收货地址
            if (Utils.IsNotNull(item.deliveryRegion)) {
                let areaId = item.deliveryRegion.split('|');
                let split = areaId[1].split(';');
                detailDeliveryAddress = split[0] + split[1] + split[2] + split[3] + item.deliveryAddress;
            } else {
                detailDeliveryAddress = item.deliveryAddress;
            }
            return { ...item, specLevelType, detailDeliveryAddress };
        });
        $('#salesEntry').empty().append(addsaleTemplate(renderEntryInfo));
    };

    //TODO : 附件信息回显
    //create周润玉
    const _images = async (file) => {
        let _imag = file.split(',');
        if (_imag) {
            if (!uploader) {
                await uploadInit();
            }
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i]).then((_res) => {
                    let _list = _vm.images;
                    _list.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i],
                    });
                    if (_res.isSucceed) {
                        let _li;
                        if (['jpg', 'jpeg', 'png', 'gif'].indexOf(_imag[i].suffix) < 0) {
                            _li = `<li class="weui-uploader__file"  data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        } else {
                            _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        }
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $('.weui-uploader__input-box').hide();
            }
            _vm.uploadCount = _sun;
        }
    };

    // 保存
    const savedata = () => {
        if (!Utils.IsNotNull(getEntryInfo)) {
            if (!Utils.IsNotNull($(`#saleOrgId`).select2('data'))) {
                return $.toptip(`请选择销售组织!`, 'warning');
            }
            if (!Utils.IsNotNull($(`#salePerId`).select2('data'))) {
                return $.toptip(`请选择销售员!`, 'warning');
            }
            if (!Utils.IsNotNull($(`#selCustomerInfos`).select2('data'))) {
                return $.toptip(`请选择客户!`, 'warning');
            }
            return $.toptip(`请添加销售订单分录信息!`, 'warning');
        }
        savetips();
    };
    // 保存提示
    const savetips = () => {
        if (Utils.IsNotNull(getUrlKey('id'))) {
            savetype = '修改';
            addstyleEntry = 'display:none';
            edistyleEntry = 'display:block';
        } else {
            savetype = '保存';
            addstyleEntry = 'display:block';
            edistyleEntry = 'display:none';
        }
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" style="${addstyleEntry}" >是否确认${savetype}该单据？</div>
                        <div class="edientry" style="${edistyleEntry}">是否确认${savetype}并保存该单据？</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '保存',
                    onClick: function () {
                        $.closeModal();
                        if (Utils.IsNotNull(getEntryInfo)) {
                            let saveStandard = [];
                            let _entries = [];
                            $.each(getEntryInfo, function (i, v) {
                                if (!Utils.IsNotNull(v.carNo)) {
                                    saveStandard.push(v);
                                }
                                v.seq = i + 1;
                                v.planQty = v.planQty || v.orderCount;
                                _entries.push({ ...v });
                            });
                            if (saveStandard.length > 0) {
                                return $.toptip(`请先完善销售订单信息`, 'warning');
                            }

                            let _attaches = [];
                            $.each(_vm.images, function (i, v) {
                                _attaches.push(v.imageId);
                            });
                            let _param = {
                                ...{ entries: _entries },
                                bizDate: _vm.bizDate,
                                saleOrgId: _vm.saleOrgId,
                                saleOrgName: _vm.saleOrgName,
                                salePerId: _vm.salePerId,
                                salePerName: _vm.salePerName,
                                salePerNumCode: _vm.salePerNumCode,
                                salePerPhone: _vm.salePerPhone,
                                cstmId: _vm.cstmId,
                                cstmName: _vm.cstmName,
                                cstmNumCode: _vm.cstmNumCode,
                                cstmPhone: _vm.cstmPhone,
                                pigType: _vm.pigType,
                                tranType: _vm.tranType,
                                totalCount: $('#totalNum').text(),
                                remark: $('#remark').val(),
                                attaches: _attaches.join(','),
                            };
                            if (Utils.IsNotNull(getUrlKey('id'))) {
                                saleOrdersAPI.ediSalesList(getUrlKey('id'), _param).then((res) => {
                                    $.toptip('请求成功。', 'success');
                                    location.href = `./saleorders.html?v=${Utils.GetTime()} `;
                                });
                            } else {
                                saleOrdersAPI.addSalesList(_param).then((res) => {
                                    $.toptip('请求成功。', 'success');
                                    location.href = `./saleorders.html?v=${Utils.GetTime()} `;
                                });
                            }
                        }
                    },
                },
            ],
        });
    };

    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat('...');
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串；
        if (str_length < len) {
            return str;
        }
    };
    // 获取地址栏的 参数
    const getUrlKey = (name) => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

    const selfAdaption = () => {
        document.addEventListener('touchstart', function (event) {
            if (event.touches.length >= 2) {
                event.preventDefault();
            }
        });

        document.addEventListener('touchmove', function (event) {
            if (event.touches.length >= 2) {
                event.preventDefault();
            }
        });
        document.addEventListener('touchend', function (event) {
            if (event.touches.length >= 2) {
                event.preventDefault();
            }
        });
    };
    // 控制返回按钮，返回的页面
    const ctlReturn = () => {
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', function () {
                history.pushState(null, null, document.URL);
                //跳转列表
                this.window.location = `./saleorders.html?v=${Utils.GetTime()} `;
            });
        }
    };

    //TODO : 附件上传
    //create周润玉
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                if (['image/jpg', 'image/jpeg', 'image/png'].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: function () {
                let formFile = new FormData();
                let upFiles = this;
                let file = publicFileDraw(this.name, _vm);
                if (file != false && file != undefined) {
                    formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                    _uploadFileDraw(formFile, upFiles, _vm, file);
                }
                //确认提交
                $('.weui-dialog__btn').on('click', function () {
                    if ($(this)[0].innerHTML == '确认') {
                        $.showLoading('上传中...');
                        let fileName = sliceFileName(upFiles);
                        let newfile = publicFileDraw(fileName, _vm);
                        if (newfile != false && newfile != undefined) {
                            formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                            _uploadFileDraw(formFile, upFiles, _vm, newfile);
                        }
                    }
                });
                return true;
            },
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter((item) => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $('.weui-uploader__input-box').hide();
                            } else {
                                $('.weui-uploader__input-box').show();
                            }
                        },
                        onCancel: function () {},
                    });
                },
            });
        });
    };

    /**
     *@file 附件上传
     *@create周润玉
     */
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile)
            .then((res) => {
                if (res.isSucceed) {
                    let _list = _vm.images;
                    _list.push({
                        id: $('#uploaderFiles li').length,
                        imageId: res.data,
                        url: upFiles.url,
                        name: newName,
                    });
                    _vm.attaches.push(res.data);
                    $('#uploaderFiles li').each(function (i) {
                        $(this).attr('data-id', _vm.images[i].id);
                        $(this).attr('data-image-id', _vm.images[i].imageId);
                        $(this).attr('data-name', _vm.images[i].name);
                        $(this).attr('data-suffix', _vm.images[i].type);
                        $(this).attr('data-url', _vm.images[i].url);
                        $(this).css({ 'background-image': `url(${_vm.images[i].url})` });
                    });
                    $('.weui-uploader__file-content').hide();
                    $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                    $.hideLoading();
                    $.closeModal();
                }
            })
            .catch((res) => {
                $('#uploaderFiles li')
                    .eq($('#uploaderFiles li').length - 1)
                    .remove();
                _vm.uploadCount = --_vm.uploadCount;
                $.toptip(res.msg, 'error');
            })
            .finally((_) => {
                $.hideLoading();
                $.closeModal();
            });
    };

    //查询销售计划分页列表
    const _querySalePlansList = () => {
        _vm._data.page.orgId = $('#saleOrgId').val();
        saleOrdersAPI.postSalePlanList(_vm._data.page).then((res) => {
            let _page = {
                searchInfo: '',
                startDate: '',
                endDate: '',
                billStatus: 3,
                orgId: $('#saleOrgId').val(),
                fitlerOrgs: _personOrg,
                pageSize: 10,
                pageIndex: _vm._data.page.pageIndex + 1,
                totalPages: res.totalPages,
            };
            _vm._data.page = Object.assign({}, _page);
            res.items.map((item) => {
                let type = _levelType.find((s) => s.value == item.pigType).displayName;
                let labhtml = `
                 <label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}"
                   data-farmOrgId="${item.farmOrgId}" data-farmOrgName="${item.farmOrgName}" data-specLevel="${item.pigType}" data-count="${item.checkCount || item.count}" data-avgWeight="${item.avgWeight}"
                    data-breedBatchId="${item.breedBatchId}" data-breedBatchName="${item.breedBatchName}">
					<input type="checkbox" class="" name="checkbox1" id="${item.id}" style="width: 25px;height: 25px;">
					<div class="" aria-hidden="true" style='margin-left: 15px;'>
						<span style="color:#4d4d4d">批次：</span><span class="lab_name" style="color:#4d4d4d">${item.breedBatchName}</span>
                        <div class="demo_badge_desc lab_numCode">
                          <span style="color:#4d4d4d">头数(头)：</span><span style="color:#ee6808">${item.checkCount || item.count}</span>&nbsp;
                          <span style="color:#4d4d4d">日龄(天)：</span><span style="color:#ee6808">${item.pigDays}</span>&nbsp;
                          <span style="color:#4d4d4d">类型：</span>${type}
                        </div>
                         <div class="demo_badge_desc lab_numCode" style="color:#4d4d4d">
                          业务日期：<span>${moment(item.bizDate).format('YYYY-MM-DD')}</span>&nbsp;
                        </div>
					</div>
				</label>`;
                $('#saleplans-list').append(labhtml);
            });
            if (_vm._data.page.pageIndex == _vm._data.page.totalPages) {
                $('#saleplans-list').append(`<div class="weui-loadmore weui-loadmore_line"><span class="weui-loadmore__tips">已经到底了</span></div>`);
                $('#saleplans-list').append(`<div style="height:110px"></div>`);
            } else if (_vm._data.page.totalPages == 0) {
                $('#saleplans-list').append(`<div class="weui-loadmore weui-loadmore_line"><span class="weui-loadmore__tips">已经到底了</span></div>`);
            }
        });
    };
})(window, document, jQuery);
